//
//  ConstantViewController.m
//  ChatDemo
//
//  Created by 度周末网络-王腾 on 15/12/21.
//  Copyright © 2015年 imac. All rights reserved.
//

#import "ConstantViewController.h"
#import "ConstantTableCell.h"
#import "AddFriendsViewController.h"
#import "ChatViewController.h"
#import "EaseApplyManager.h"

@interface ConstantViewController () <EMChatManagerDelegate>

@property (strong, nonatomic) IBOutlet UIView *tableHeaderView;


@property (nonatomic , strong) NSMutableArray *contactsSource;
- (IBAction)newBuddyBtnAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UITableView *mainTable;

@end

@implementation ConstantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.contactsSource = [[NSMutableArray alloc ] init];
    [self registerNotifications];
    [self tableViewDidTriggerHeaderRefresh];
    
    self.countLabel.layer.cornerRadius = 10.0f;
    self.countLabel.layer.masksToBounds = YES;
    
    // 好友申请数量提示
    [self setupUntreatedApplyCount];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applyBuddyCountChage:) name:KNOTIFICATION_APPLYCountChange object:nil];
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];
    
    self.tableHeaderView.frame = CGRectMake(0, 0, self.view.frame.size.width, 71);
    self.mainTable.tableHeaderView = self.tableHeaderView;
    [self tableViewFooterLineHidden:self.mainTable];
}

#pragma mark - login changed
- (void)loginStateChange:(NSNotification *)notification
{
    BOOL isAutoLogin = [[[EaseMob sharedInstance] chatManager] isAutoLoginEnabled];
    BOOL loginSuccess = [notification.object boolValue];
    // 登陆成功加载主窗口控制器
    if (isAutoLogin || loginSuccess) {
        [self tableViewDidTriggerHeaderRefresh];
    }
}

/**
 *  好友申请数量提示
 */
- (void)setupUntreatedApplyCount
{
    NSInteger unreadCount = [[[EaseApplyManager shareManager]loadApplyFromDB]count];
    self.countLabel.text = @(unreadCount).stringValue;
    if (unreadCount > 0) {
        self.countLabel.hidden = NO;
    }else{
        self.countLabel.hidden = YES;
    }
}

/**
 *  好友申请数量提示
 */
-(void)applyBuddyCountChage:(NSNotification *)note{
    
    NSNumber *count = note.object;
    self.countLabel.text = count.stringValue;
    if ([count integerValue] > 0) {
        self.countLabel.hidden = NO;
    }else{
        self.countLabel.hidden = YES;
    }
}

-(void)registerNotifications{
    [self unregisterNotifications];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}


- (void)didUpdateBuddyList:(NSArray *)buddyList
            changedBuddies:(NSArray *)changedBuddies
                     isAdd:(BOOL)isAdd{
    [self reloadDataSource];
}

/*!
 @method
 @brief 接受好友请求成功的回调
 @discussion
 @param username 登录用户接受了"username发过来的好友请求"成功的回调
 */
- (void)didAcceptBuddySucceed:(NSString *)username{
     [self tableViewDidTriggerHeaderRefresh];
}

/*!
 @method
 @brief 登录的用户被好友从列表中删除了
 @discussion
 @param username 删除的好友username
 */
- (void)didRemovedByBuddy:(NSString *)username{
     [self tableViewDidTriggerHeaderRefresh];
}

- (void)reloadDataSource
{

    [self.contactsSource removeAllObjects];
    
    NSArray *buddyList = [[EaseMob sharedInstance].chatManager buddyList];
    NSArray *blockList = [[EaseMob sharedInstance].chatManager blockedList];
    for (EMBuddy *buddy in buddyList) {
        if (![blockList containsObject:buddy.username]) {
            [self.contactsSource addObject:buddy];
        }
    }
    
  
    [self.mainTable reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.contactsSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ConstantTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConstantTableCell"];
    EMBuddy *buddy = [self.contactsSource objectAtIndex:indexPath.row];
    cell.userName.text = buddy.username;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    EMBuddy *buddy = [self.contactsSource objectAtIndex:indexPath.row];
    ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:buddy.username conversationType:eConversationTypeChat];
    chatController.title = buddy.username;
    chatController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatController animated:YES];
}

- (void)tableViewDidTriggerHeaderRefresh
{

    __weak ConstantViewController *weakSelf = self;
    [[[EaseMob sharedInstance] chatManager] asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
     
            if (error == nil) {
                [self.contactsSource removeAllObjects];
                [self.contactsSource addObjectsFromArray:buddyList];
                
                [self.mainTable reloadData];
                
            }
            else{
                [weakSelf showHint:NSLocalizedString(@"loadDataFailed", @"Load data failed.")];
            }
          
        });
    } onQueue:nil];
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EMBuddy *model = [self.contactsSource objectAtIndex:indexPath.row];
        EMError *error = nil;
        [[EaseMob sharedInstance].chatManager removeBuddy:model.username removeFromRemote:YES error:&error];
        if (!error) {
            [[EaseMob sharedInstance].chatManager removeConversationByChatter:model.username deleteMessages:YES append2Chat:YES];
            
            [tableView beginUpdates];
            [self.contactsSource removeObject:model];
            [tableView  deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView  endUpdates];
        }
        else{
            [self showHint:[NSString stringWithFormat:NSLocalizedString(@"deleteFailed", @"Delete failed:%@"), error.description]];
            [tableView reloadData];
        }
        
    }
}


- (IBAction)newBuddyBtnAction:(UIButton *)sender {
    AddFriendsViewController *addFriend = [self.storyboard instantiateViewControllerWithIdentifier:@"AddFriendsViewController"];
    [self.navigationController pushViewController:addFriend animated:YES];
    
}

@end
